package com.example.backend.config;

import com.example.backend.condition.OnRedisAvailableCondition;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * Redis 缓存配置类
 *
 * @author mhwssad
 */
@Configuration
@Conditional(OnRedisAvailableCondition.class)
@ConditionalOnProperty(name = "spring.redis.host")
public class RedisCacheConfig {

    /**
     * 配置 RedisCacheManager，设置缓存默认过期时间和序列化方式
     */
    @Bean
    @Primary
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        // 创建JSON序列化器
        Jackson2JsonRedisSerializer<Object> serializer = createJsonSerializer();

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
                .disableCachingNullValues()
                .prefixCacheNameWith("cache:");

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .build();
    }

    /**
     * 配置 RedisTemplate，使用 JSON 序列化方式
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 复用 JSON 序列化器配置
        Jackson2JsonRedisSerializer<Object> jacksonSerializer = createJsonSerializer();

        // key 使用 String 序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        // hash 的 key 也使用 String 序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        // value 序列化方式使用 jackson
        template.setValueSerializer(jacksonSerializer);
        // hash 的 value 序列化方式使用 jackson
        template.setHashValueSerializer(jacksonSerializer);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 创建通用的 JSON 序列化器
     */
    private Jackson2JsonRedisSerializer<Object> createJsonSerializer() {
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper mapper = new ObjectMapper();

        // 设置序列化可见性和类型信息
        configureObjectMapper(mapper);

        serializer.setObjectMapper(mapper);
        return serializer;
    }

    /**
     * 配置 ObjectMapper 的公共方法
     */
    private void configureObjectMapper(ObjectMapper mapper) {
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL);
    }
}